<template>
  <div>
    <el-card>
      <div class="search">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="全部"
              clearable
              style="width: 200px"
            >
              <el-option label="待审核" value="1" />
              <el-option label="审核通过" value="2" />
              <el-option label="内容违规" value="3" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleData"  v-hasPerm="['resource:instrument:get']"
              ><i-ep-search />搜索</el-button
            >
            <el-button @click="resetQuery">
              <i-ep-refresh />
              重置</el-button
            >
          </el-form-item>
        </el-form>
      </div>

      <div>
        <el-button
          type="danger"
          :disabled="ids.length === 0"
          @click="deleteClick()"
          v-hasPerm="['resource:instrument:del']"
          ><i-ep-delete />删除</el-button
        >
      </div>
    </el-card>

    <el-card>
      <div>
        <el-form>
          <el-form-item>
            <el-table
              :data="dataList"
							:header-cell-style="{'text-align':'center'}"
    :cell-style="{'text-align':'center'}"
              style="width: 100%"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="40" align="center" />
              <el-table-column
                fixed
                type="index"
                :index="indexMethod"
                label="序号"
                width="60"
              />
              <el-table-column prop="title" label="标题" width="150" />
              <!-- <el-table-column prop="describe" label="描述" width="120" /> -->

              <el-table-column prop="status" label="状态" width="80">
                <template #default="scope">
                  <span v-if="scope.row.status === 1">待审核</span>
                  <span v-else-if="scope.row.status === 2">审核通过</span>
                  <span v-else-if="scope.row.status === 3">内容违规</span>
                </template>
              </el-table-column>

              <el-table-column
                prop="authorUsername"
                label="发布人"
                width="80"
              />
              <el-table-column
                prop="downloadRecord"
                label="下载次数"
                width="80"
              />
              <el-table-column label="图片" width="170px">
                <template #default="scope">
                  <!-- <img
                    :src="scope.row.cover"
                    alt=""
                    style="width: 100%; height: 100px"
                  /> -->
									<el-image
      							style="width: 100%; height: 100px"
     							 :src="scope.row.cover"
     							 :zoom-rate="1.2"
      							:max-scale="7"
     							 :min-scale="0.2"
     							 :preview-src-list="[scope.row.cover]"
										:preview-teleported="true"
										hide-on-click-modal
   							 />
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="发布时间" width="160" />

              <el-table-column fixed="right" label="操作" width="400">
                <template #default="scope">
                  <el-button type="primary" @click="detailsClick(scope.row.id)"   v-hasPerm="['resource:instrument:get']"
                    >详情</el-button
                  >

                  <el-button type="success" @click="downloadClick(scope.row.id)" v-hasPerm="['resource:instrument:download']"
                    >下载</el-button
                  >

                  <el-button type="warning" @click="openDialog(scope.row)"  v-hasPerm="['resource:instrument:update']"
                    >编辑</el-button
                  >

                  <el-button type="danger" @click="deleteClick(scope.row.id)"  v-hasPerm="['resource:instrument:del']"
                    >删除</el-button
                  >
                  <el-button
                    type="info"
                    @click="handleClick(scope.row)"
										v-hasPerm="['resource:instrument:update']"
                    >审核</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页搜索 -->
            <div
              style="
                display: flex;
                justify-content: center;
                width: 100%;
                margin-top: 15px;
              "
            >
              <el-pagination
                background
                layout="sizes, prev,slot, next, jumper"
                :page-count="pageTotal"
                :page-sizes="[10, 20, 30, 50]"
                :current-page="activePager"
                @update:current-page="pageChange"
                @update:page-size="sizeChange"
                :default-current-page="1"
                :default-page-size="10"
              >
                <div class="pagination">
                  <span
                    class="pagination__item"
                    :class="{ active: activePager === pager }"
                    v-for="pager in pageArr"
                    :key="pager"
                    @click="pageChange(pager)"
                  >
                    {{ pager }}
                  </span>
                </div>
              </el-pagination>
            </div>
            <!-- 分页搜索 -->
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <el-dialog v-model="dialog.visible" title="详细信息">
      <el-table :data="detailList" style="width: 100%">
        <el-table-column type="expand">
          <template #default="props">
            <div m="7">
              <p m="t-0 b-2">资源标签: {{ props.row.tags }}</p>
              <p m="t-0 b-2">资源类型: {{ props.row.type }}</p>
              <p m="t-0 b-2">资源费用: {{ props.row.cost }}</p>
              <p m="t-0 b-2">资源的路径或链接: {{ props.row.path }}</p>
              <p m="t-0 b-2">资源可见性: {{ props.row.visible }}</p>
              <p m="t-0 b-2">
                资源管理者用户名: {{ props.row.managerUsername }}
              </p>
              <p m="t-0 b-2">资源创建时间: {{ props.row.createTime }}</p>

              <h3>初始界面显示信息</h3>
              <el-table :data="detailList">
                <el-table-column label="id" prop="id" />
                <el-table-column label="资源标题" prop="title" />
                <!-- <el-table-column label="描述" prop="describe" /> -->
                <el-table-column prop="status" label="状态" width="120">
                  <template #default="scope">
                    <span v-if="scope.row.status === 1">待审核</span>
                    <span v-else-if="scope.row.status === 2">审核通过</span>
                    <span v-else-if="scope.row.status === 3">内容违规</span>
                  </template>
                </el-table-column>
                <el-table-column label="发布人" prop="authorUsername" />
                <el-table-column label="下载次数" prop="downloadRecord" />
                <el-table-column label="资源描述" prop="describe" />
                <el-table-column label="图片" width="150px">
                  <template #default="scope">
                    <img
                      :src="scope.row.cover"
                      alt=""
                      style="width: 100px; height: 100px"
                    />
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="发布时间" prop="createTime" />
        <el-table-column label="发布人" prop="authorUsername" />
      </el-table>

      <el-form :model="formData">
        <el-radio-group   v-model="formData.status">
          <el-radio :label="1">待审核</el-radio>
          <el-radio :label="2">审核通过</el-radio>
          <el-radio :label="3">内容违规</el-radio>
        </el-radio-group>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialog.visible = false">取消</el-button>
          <el-button @click="axamineSubmit"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog v-model="editDialog.visible" title="编辑"  width="100%" @close="cloceEditDialog">
      <!-- <div style="margin: 20px" />
      <el-form
        ref="detailFormRef"
        :rules="rules"
        :model="formData"
        :label-position="labelPosition as 'left' "
        label-width="100px"
        style="max-width: 460px"
      >
        <el-form-item label="序号">
          <el-input v-model="formData.id" disabled />
        </el-form-item>

        <el-form-item label="用户">
          <el-input v-model="formData.authorUsername" />
        </el-form-item>

        <el-form-item label="标题">
          <el-input v-model="formData.title" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="formData.describe" />
        </el-form-item>
        <el-form-item label="资源类型">
          <el-input v-model="formData.type" />
        </el-form-item>
        <el-form-item label="资源费用">
          <el-input v-model="formData.cost" />
        </el-form-item>
        <el-form-item label="资源的可见性">
          <el-input v-model="formData.visible" />
        </el-form-item>
        <el-form-item label="资源的名称">
          <el-input v-model="formData.resourceName" />
        </el-form-item>

        <el-form-item label="资源的状态">
          <el-input
            v-model="formData.status"
            :value="getStatusText(formData.status)"
            disabled
          />
        </el-form-item>

        <el-form-item label="管理者用户名">
          <el-input v-model="formData.managerUsername" />
        </el-form-item>
        <el-form-item label="资源下载记录">
          <el-input v-model="formData.downloadRecord" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template> -->
  <div class="box">
    <div class="main" v-loading="loading">
      <h1 class="title">修改资源</h1>
      <el-form
        :model="data.ruleForm"
        :rules="rule"
        ref="ruleFormRef"
        label-width="90px"
        class="demo-ruleForm"
        size="large"
        label-position="left"
        validate-on-rule-change
        style="width: 100%; padding: 20px 20px 0px"
      >
        <el-form-item label="资源名" prop="title" style="width: 100%">
          <el-input
            style="width: 100%"
            type="text"
            v-model="data.ruleForm.title"
            placeholder="输入名称..."
          ></el-input>
        </el-form-item>

        <el-form-item label="描述" style="width: 100%">
          <el-input type="textarea" v-model="data.ruleForm.describe"></el-input>
        </el-form-item>

        <el-form-item label="封面" prop="cover">
          <el-upload
            :action="File_API.OTHER_URL"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            class="avatar-uploader"
						:headers="{'Authorization': 'Bearer ' + userStore.token}"
          >
            <img v-if="data.imageUrl" :src="data.imageUrl" class="avatar" />
            <el-icon
              v-else
              name="UploadFilled"
              class="avatar-uploader-icon"
            ></el-icon>
            <el-icon v-else class="avatar-uploader-icon">
              <UploadFilled />
            </el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="资源" prop="resource">
          <el-upload
            :action="File_API.COURSE_URL"
						:headers="{'Authorization': 'Bearer ' + userStore.token}"
            :show-file-list="false"
            :on-success="handleResourceSuccess"
            :before-upload="beforeResourceUpload"
            class="upload-demo"
          >
            <span style="color: gray" v-if="data.ruleForm.resourceName">
              {{ data.ruleForm.resourceName }}
            </span>
            <el-icon
              v-else
              name="UploadFilled"
              class="avatar-uploader-icon"
            ></el-icon>
            <el-icon v-else class="avatar-uploader-icon">
              <UploadFilled />
            </el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="资源类型" prop="type">
        
          <el-cascader
            v-model="data.selectedOptions"
            :props="data.prop"
            :show-all-levels="false"
            @change="selectType"
          ></el-cascader>
        </el-form-item>

        <el-form-item label="标签">
   
          <el-popover
            placement="top"
            width="150"
            trigger="click"
            v-model="data.visibleAdd"
          >
            <el-input
              placeholder="请输入标签"
              @blur="handleInput(data.tag)"
              v-model="data.tag"
              clearable
            ></el-input>
            <template #reference>
              <el-button>添加资源标签</el-button>
            </template>
          </el-popover>

          <el-popover
            v-for="(tag, index) in data.ruleForm.tags1"
            :key="index"
            placement="top"
            width="150"
            trigger="click"
            v-model="data.visibleTag"
          >
            <div style="text-align: center">
              <el-button @click="deleteTag(index)">删除</el-button>
            </div>
            <template #reference>
              <el-button>{{ tag }}</el-button>
            </template>
          </el-popover>
        </el-form-item>

				<!-- <el-form-item label="审核状态">
						<el-select
              v-model="data.ruleForm.status"
              placeholder="请选择审核状态"
              clearable
              style="width: 200px"
            >
              <el-option label="待审核" value="1" />
              <el-option label="审核通过" value="2" />
              <el-option label="内容违规" value="3" />
            </el-select>
					</el-form-item> -->

        <el-form-item label="可见范围">
          <el-radio-group v-model="data.ruleForm.visible">
            <el-radio
              v-for="option in data.optionsVisible"
              :key="option.id"
              :label="option.id"
            >
              {{ option.visibleRange }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item style="width: 100%">
          <div style="width: 100%; display: flex; justify-content: center">
            <el-button type="primary" round @click="commit(ruleFormRef)">
              <el-icon>
                <Edit />
              </el-icon>
              修改资源
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
    </el-dialog>

    <!-- 审核 -->
    <el-dialog v-model="dialogExamineVisible.visible" title="审核信息">
      <el-form :model="formData">
        <el-radio-group v-model="formData.status">
          <el-radio :label="2">审核通过</el-radio>
          <el-radio :label="3">内容违规</el-radio>
        </el-radio-group>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogExamineVisible.visible = false"
            >取消</el-button
          >
          <el-button type="primary" @click="axamineSubmit"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {
  getResource,
  deleteAdmin,
  updatainfo,
  getDetail,
  examine,
  downloadResource,
} from "@/api/resource";
import { Article, getListInfo } from "@/api/resource/type";
import { reactive, ref, onMounted, defineComponent,  } from "vue";
import { getCategoryResource1 } from '@/api/category'
import { getCategoryResource2 } from '@/api/category'
import {  getVisible } from '@/api/blog'
import axios from 'axios'
import type { FormInstance, FormRules } from 'element-plus'
import { resourceUpdate,getStatus } from '@/api/resource'
import {
  ElMessageBox,
  genFileId,
  UploadInstance,
  UploadProps,
  UploadRawFile,
} from 'element-plus'
import {UploadFilled,Promotion,Plus,Edit} from '@element-plus/icons-vue'
import { useUserStoreHook } from '@/store/modules/user'
import { File_API } from '@/api/file'

defineComponent({
  components: {
		UploadFilled,
		Promotion,
		Plus,
		Edit,
  },
});

const userStore = useUserStoreHook()
const dataList = ref<Article[]>();
const detailList = ref<Article[]>();
const loading = ref(false);
const dialogTableVisible = ref(false);

//总共页数
const pageTotal = ref(0);
//后端传来的页码数组
const pageArr = ref([]);
//当前页码
const activePager = ref(1);

const ids = ref([]);

const formLabelWidth = "140px";

const queryParams = reactive<getListInfo>({
  pageNum: 1,
  pageSize: 10,
});

const indexMethod = (index: number) => {
  return index + 10 * activePager.value - 9;
};

//审核弹框
const dialogExamineVisible = reactive<DialogOption>({
  visible: false,
});

const dialog = reactive<DialogOption>({
  visible: false,
});

//编辑弹框
const editDialog = reactive<DialogOption>({
  visible: false,
});

/**
 * 行checkbox change事件
 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

let formData = reactive<Article>({
  authorUsername: "",
  title: "",
  describe: "",
  tags: "",
  type: 0,
  path: "",
  cost: 0,
  visible: 0,
  resourceName: "",
  status: 0,
  managerUsername: "",
  downloadRecord: 0,
});

const queryFormRef = ref(ElForm); // 查询表单

const labelPosition = ref("right");

const detailFormRef = ref(ElForm); // 用户表单

const markdownText = ref("");
const renderedMarkdown = ref("");

const rules = reactive({
  id: [{ required: true, message: "id不能为空", trigger: "blur" }],
  title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
  describe: [{ required: true, message: "用户角色不能为空", trigger: "blur" }],
  type: [{ required: true, message: "资源的类型不能为空", trigger: "blur" }],
  path: [{ required: true, message: "路径不能为空", trigger: "blur" }],
  visible: [
    { required: true, message: "资源的可见性不能为空", trigger: "blur" },
  ],
  resourceName: [
    { required: true, message: "资源的名称不能为空", trigger: "blur" },
  ],
});

//判断状态
function getStatusText(status?: number) {
  if (status === 1) {
    return "待审核";
  } else if (status === 2) {
    return "审核成功";
  } else if (status === 3) {
    return "内容违规";
  } else {
    return "";
  }
}

//删除
async function deleteClick(id?: number) {
  const adminIds = [id || ids.value] as number[];
  if (!adminIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }
  await ElMessageBox.confirm("确认删除资源?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    deleteAdmin(adminIds).then(() => {
      ElMessage.success("删除成功");
			handleData();
    });
  });
}

//审核弹框
async function handleClick(row: Article) {
  dialogExamineVisible.visible = true;
  await Object.assign(formData, row);
}

async function axamineSubmit() {
  loading.value = true;
  await examine(formData.id, formData.status)
    .then(() => {
      ElMessage.success("审核成功");
      closeDialog();
      resetQuery();
    })
    .finally(() => (loading.value = false));
}

//打开弹窗
async function openDialog(row: any) {
  editDialog.visible = true;
  editDialog.title = "修改数据";
  // Object.assign(formData, row);
	data.ruleForm.id =  row.id;
  data.ruleForm.title =   row.title;
	data.ruleForm.describe =   row.describe;
	data.ruleForm.tags1 =   row.tags1;
	data.ruleForm.cover =   row.cover;
	data.ruleForm.type =   row.type;
	data.ruleForm.path =   row.path;
	data.ruleForm.cost =   row.cost;
	data.ruleForm.visible =   row.visible;
	data.ruleForm.resourceName =   row.resourceName;
	data.ruleForm.status =   row.status;
	data.imageUrl =  row.cover;
	data.resourceUrl = row.path;
}


function cloceEditDialog() {
	editDialog.visible = false;
}


//修改数据提交
async function handleSubmit() {
  await detailFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      updatainfo(formData)
        .then(() => {
          ElMessage.success("修改用户成功");
          closeDialog();
          resetQuery();
        })
        .finally(() => (loading.value = false));
    }
  });
}
/**
 * 下载资源
 */

function downloadClick(id: number) {
  console.log(12345);
  loading.value = true;
  downloadResource(id)
    .then(() => {
      ElMessage.success("下载成功成功");
      handleData();
    })
    .finally(() => (loading.value = false));
}

/**
 *
 * @param id 重置查询
 */
function resetQuery() {
  queryFormRef.value.resetFields();
  handleData();
}

//详情
async function detailsClick(id: number) {
  dialog.visible = true;
  await getDetail(id).then(({ data }) => {
    detailList.value = [data.resource];
    Object.assign(formData, data.resource);
  });
}

function closeDialog() {
  editDialog.visible = false;
  dialog.visible = false;
  dialogExamineVisible.visible = false;
  handleData();
}

//获取数据
async function handleData() {
  loading.value = true;
  await getResource(queryParams)
    .then(({ data }) => {
      dataList.value = data.resources;
      pageTotal.value = data.navigatepageNums[data.navigatepageNums.length - 1];
      pageArr.value = data.navigatepageNums;
    })
    .catch((error) => {
      console.error("Error:", error);
    })
    .finally(() => {
      loading.value = false;
    });
}

async function pageChange(pageNum: number) {
  queryParams.pageNum = pageNum;
  activePager.value = pageNum;
  handleData();
}

async function sizeChange(sizeNum: number) {
  queryParams.pageSize = sizeNum;
  handleData();
}

onMounted(() => {
  handleData();
	GetVisible();
	GetStatus()
});



//修改资源模块代码

const ruleFormRef = ref<FormInstance>()
const upload = ref<UploadInstance>()
const disable = ref<boolean>(true)
const data = reactive({
  //表单验证
  ruleForm: {
  		 id: 0,
 			 title: "",
 			 describe: "",
 			 tags1: [],
 			 cover: "",
 			 type: 0,
 			 path: "",
 			 cost: 0,
 			 visible: 0,
 			 resourceName: "",
			 status: 0,
  },

  //封面显示
  imageUrl: '',

  //资源显示
  resourceUrl: '',

  //类型
  selectedOptions: [],

  prop: {
    lazy: true,
    expandTrigger: 'hover',
    // checkStrictly: true,
    lazyLoad(node: any, resolve: any) {
      setTimeout(() => {
        if (node.level == 0) {
          getCategoryResource1()
            .then((res) => {
              console.log(res)
              const firstLevelOptions = res.data.resourceTypes.map((item) => {
                return {
                  value: item.id,
                  label: item.name,
                  leaf: false,
                  id: item.id,
                }
              })
              resolve(firstLevelOptions)
            })
            .catch((error) => {})
        } else if (node.level == 1) {
          console.log(node.data.id)

          getCategoryResource2(node.data.id)
            .then((res) => {
              console.log(res)
              const childOptions = res.data.resourceTypes.map((item) => {
                return {
                  value: item.id,
                  label: item.name,
                  leaf: true,
                  id: item.id,
                }
              })
              resolve(childOptions)
            })
            .catch((error) => {})
        }
      }, 1000)
    },
  },

  //可见范围
  optionsVisible: [],
  visibleAdd: false,

  visibleTag: false,
  tag: '', //虚设

// 	//审核
// 	 selectedStatus :'',
//  optionsStatus : [
//   {
//     value: 'Option1',
//     label: 'Option1',
//   },
//   {
//     value: 'Option2',
//     label: 'Option2',
//   },
//   {
//     value: 'Option3',
//     label: 'Option3',
//   },
//   {
//     value: 'Option4',
//     label: 'Option4',
//   },
//   {
//     value: 'Option5',
//     label: 'Option5',
//   },
// ]

})

const validateType = (rule: any, value: any, callback: any) => {
  console.log('value', value, data.ruleForm.type)
  if (value === 0) {
    return callback(new Error('请选择一个类型'))
  } else {
    callback()
  }
}

const validateContent = (rule: any, value: any, callback: any) => {
  if (value === '') {
    return callback(new Error('请输入内容！！'))
  } else {
    callback()
  }
}

const rule = reactive<FormRules<typeof data.ruleForm>>({
  title: [{ required: true, message: '请输入名称！', trigger: 'blur' }],
  type: [{ required: true, validator: validateType, trigger: 'blur' }],
  describe: [{ required: true, validator: validateContent, trigger: 'blur' }],
})

const handleInput = (value) => {
  data.ruleForm.tags1.push(value)
  // data.visible = false;
  data.tag = ''
}

const deleteTag = (index) => {
  data.ruleForm.tags1.splice(index, 1)
}

// onMounted(async () => {
//   loading.value = true
//   GetVisible()

//   console.log('进入编辑...')
//   try {
//     const { data: res } = await getResourceDetail(Number(route.params.id))
//     data.ruleForm.id = Number(route.params.id)
//     data.ruleForm.title = res.resource.title
//     data.ruleForm.authorUsername = res.resource.authorUsername
//     data.ruleForm.type = res.resource.type
//     data.ruleForm.tags1 = res.resource.tags1
//     data.ruleForm.visible = res.resource.visible
//     data.ruleForm.cover = res.resource.cover
//     data.imageUrl = data.ruleForm.cover
//     data.ruleForm.resourceName = res.resource.resourceName
//     data.ruleForm.describe = res.resource.describe
//     data.ruleForm.path = res.resource.path
//     console.log(data.ruleForm)
//   } catch (error) {
//     Promise.reject(error)
//   }
//   loading.value = false
// })

const GetVisible = async () => {
  try {
    const res = await getVisible()
    console.log(res)
    data.optionsVisible = res.data.visibleTypeList
  } catch (error) {
    Promise.reject(error)
  }
}

const GetStatus = async () => {
  try {
    const res = await getStatus()
    console.log(res)
    // data.optionsVisible = res.data.visibleTypeList
  } catch (error) {
    Promise.reject(error)
  }
}

const selectType = (value) => {
  console.log('hello', data.selectedOptions[1])
  data.ruleForm.type = data.selectedOptions[1]
}

const handleAvatarSuccess = (res, file) => {
  data.imageUrl = URL.createObjectURL(file.raw)
  console.log(res.data.url)
  data.ruleForm.cover = res.data.url
}

const beforeAvatarUpload = () => {}

const handleResourceSuccess = (res, file) => {
  data.resourceUrl = URL.createObjectURL(file.raw)
  console.log('resourceUrl:', data.resourceUrl)
  console.log('资源返回路径:', res.data.url)
  data.ruleForm.path = res.data.url
  //名称提取
  data.ruleForm.resourceName = res.data.url.slice(
    res.data.url.lastIndexOf('.com/') + 5,
  )
  console.log(data.ruleForm.resourceName)
}

const beforeResourceUpload = () => {}

const $imgAdd = (pos, $file) => {
  // 第一步.将图片上传到服务器.
  var formdata = new FormData()
  formdata.append('image', $file)
  axios({
    url: `${`http://localhost:8002/file/fileoss/upload`}`,
    method: 'post',
    data: formdata,
    headers: { 'Content-Type': 'multipart/form-data' },
  }).then((url) => {
    // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
    // $vm.$img2Url 详情见本页末尾
    $vm.$img2Url(pos, url)
  })
}

const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
  console.log(file, uploadFiles, '资源删除')
  disable.value = false
}

const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)

  console.log(data.ruleForm.resourceName)
  console.log(file)
}

const commit = (formEl: FormInstance | undefined) => {
  // console.log('提交')
  if (!formEl) {
    console.log('表单没找到')
    return
  }
  formEl.validate(async (valid) => {
    if (valid) {
      console.log('submit!')
      try {
        const res = await resourceUpdate(data.ruleForm)
        ElMessageBox.alert(res.message, '温馨提示', {
          confirmButtonText: '确认',
          callback: (action: Action) => { handleData();cloceEditDialog();},
        })
      } catch (error) {
        Promise.reject(error)
      }
    } else {
      console.log('error submit!')
      return false
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}


</script>

<style scoped lang="scss">

h1 {
  color: blue;
}
.box {
  display: flex;
  justify-content: center;
  width: 100%;

  .main {
    width: 1180px;
    margin: 0px auto;
    border-radius: 8px;
    background-color: white;
    padding: 26px 32px;

    .title {
      font-size: 20px;
      font-weight: bold;
      color: var(--el-text-color-primary);
    }
  }
}

.pagination {
  display: flex;
  justify-content: center;
}

.pagination__item {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 30px;
  height: 30px;
  margin: 0 5px;
  cursor: pointer;
  border: 1px solid #ccc;
}

.pagination__item.active {
  color: white;
  background-color: #4593ff;
}
</style>

<!-- 饿了么的样式写在这里避免不生效 -->
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #807d7d;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 268px;
  height: 178px;
  line-height: 150px;
  text-align: center;
}
.avatar {
  width: 268px;
  height: 178px;
  display: block;
}

.rounded-button {
  display: inline-block;
  padding: 13px 23px 13px 23px; /* 根据需要调整按钮的内边距 */
  border-radius: 17px; /* 设置按钮的圆角半径 */
  background-color: #f0f0f0; /* 设置按钮的背景色 */
  color: #333; /* 设置按钮的文字颜色 */
  font-size: 16px; /* 设置按钮的文字大小 */
  text-decoration: none; /* 去掉按钮的下划线 */
  cursor: pointer; /* 鼠标移上按钮时显示手形光标 */
}

/* 鼠标移上按钮时的样式 */
.rounded-button:hover {
  background-color: #c1daf3; /* 修改按钮的背景色 */
  color: #fff; /* 修改按钮的文字颜色 */
}
</style>
